package com.zbf.dbconfig;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

/**
 * @author: LCG
 * 作者: LCG
 * 日期: 2021/3/24  0:11
 * 描述:
 */
@Configuration
@MapperScan(basePackages = {"com.zbf.dao"},sqlSessionFactoryRef = "sqlsessionFactory1")
public class Db1Config {

    @Autowired
    private Db1 db1;

    @Bean(name = "dataSource1")
    @Primary
    public DataSource getDataSource(){

        DataSource build = DataSourceBuilder.create()
                .driverClassName(db1.getDriverClassName())
                .password(db1.getPassword())
                .username(db1.getUserName())
                .url(db1.getUrl())
                .build();

        return build;
    }

    @Bean(name = "datasourceTransactionManager1")
    @Primary
    public PlatformTransactionManager getDataSourceTransactionManager(@Qualifier("dataSource1") DataSource dataSource){
       return new DataSourceTransactionManager(dataSource);
    }


    @Bean("sqlsessionFactory1")
    @Primary
    public SqlSessionFactory getSqlSessionFactory(@Qualifier("dataSource1") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().
                getResources("classpath*:/mapper/db1/*.xml"));

        return sqlSessionFactoryBean.getObject();
    }


}
